package com.jenkins;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author 揭光智
 * @date 2020/04/08
 */
public class ReadFileThread extends Thread {
    private List<String> ops = new ArrayList<>();

    private Map<String, Integer> total = new HashMap<>();
    private final int UNDEFINED = -1;

    private int lastTime = UNDEFINED;

    private boolean invalid = false;

    // private final String FLAG_X = "ABS_MT_POSITION_X";
    // private final String FLAG_Y = "ABS_MT_POSITION_Y";

    private final String FLAG_X = "ABS_MT_POSITION_X";
    private final String FLAG_Y = "ABS_MT_POSITION_Y";


    @Override
    public void run() {

        File file = createFile("F:/test/test.txt");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {

            while (!Thread.currentThread().isInterrupted()) {

                ops = reader.lines()
                        .filter(line -> {
                            System.out.println(line);
                            return true;
                        })
                        .filter(line -> (line.contains(FLAG_X) || line.contains(FLAG_Y))
                                && lastTime != dealWithTime(line))
                        .collect(Collectors.toList());

                if (invalid) {
                    ops.clear();
                    invalid = false;
                    System.out.println("本次操作无效:" + ops.size() + "  " + total.size());
                    continue;
                }


                if (ops.size() > 0) {
                    // System.out.println("ops:size:" + ops.size() / 2);

                    for (int i = 0; i < ops.size() - 1; i += 2) {
                        getXy(ops.get(i), ops.get(i + 1));
                    }
                    lastTime = dealWithTime(ops.get(ops.size() - 1));
                    //  System.out.println("lastTime:" + lastTime);
                    ops.clear();
                }


                if (total.size() > 0) {
                    // System.out.println(JSON.toJSONString(total));
                    Set<String> keys = total.keySet();
                    int max = 0;
                    String xY = "";
                    for (String key : keys) {
                        if (total.get(key) > max) {
                            max = total.get(key);
                            xY = key;
                        }
                    }
                    xY = xY.replace("(", "");
                    xY = xY.replace(")", "");
                    String[] xYs = xY.split(",");
                    //  http(Integer.parseInt(xYs[0]), Integer.parseInt(xYs[1]));
                    System.out.println("(" + Integer.parseInt(xYs[0]) + "," + Integer.parseInt(xYs[1]) + ")");
                    total.clear();
                }
                //System.out.println(JSON.toJSONString(total));
                //TimeUnit.SECONDS.sleep(1);
                // System.out.println("没读到内容");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getXy(String xLine, String yLine) {
        int x = UNDEFINED;
        int y = UNDEFINED;
        if (xLine.contains(FLAG_X)) {
            String[] xS = xLine.split(" ");
            if (xS.length >= 16) {
                String xStr = xS[xS.length - 1];
                String xBigInteger = new BigInteger(xStr, 16).toString();
                if (isNumeric(xBigInteger)) x = Integer.parseInt(xBigInteger) - 1;
            }
        }

        if (yLine.contains(FLAG_Y)) {
            String[] yS = yLine.split(" ");
            if (yS.length >= 16) {
                String yStr = yS[yS.length - 1];
                String yBigInteger = new BigInteger(yStr, 16).toString();
                if (isNumeric(yBigInteger)) y = Integer.parseInt(yBigInteger) - 83;
            }
        }

        if (x > 0 && y > 0) {
            String key = "(" + x + "," + y + ")";
            Integer count = total.computeIfAbsent(key, v -> 0);
            total.put(key, count + 1);
        }
    }


    private void http(int x, int y) {
        System.out.println("x:" + x + "y:" + y);
        OperateClickV2Param param = new OperateClickV2Param();
        param.setAccount("7");
        param.setSleepTime(500);
        param.setClickRange(3);
        param.setRemarks("测试点击");
        param.setX(y);
        param.setY(x);

        OkHttpUtils utils = new OkHttpUtils();
        try {
            String url = "https://lucky.api.itnaodong.com/api/v2/analysis-engine/click";
            String result = utils.post(url, JSON.toJSONString(param));
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private int dealWithTime(String line) {
        int iTime = 0;
        String[] pos = line.split(" ");
        String time = pos[2];
        time = time.replace("]", "");
        if (isNumeric(time)) {
            iTime = (int) Double.parseDouble(time);
        } else {
            System.out.println("这不是一个数字:" + line);
            invalid = true;
        }
        return iTime;
    }

    private boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^[0-9]+(.[0-9]+)?$");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }


    private File createFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}
